package com.it.emall.service.impl;

import com.it.emall.mapper.LikesMapper;
import com.it.emall.mapper.RecipeMapper;
import com.it.emall.service.LikesService;
import com.it.emall.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LikesServiceImpl implements LikesService {


    @Autowired
    private RecipeMapper recipeMapper;

    @Autowired
    private LikesMapper likesMapper;


    @Override
    public int toggleLike(int userId, int recipeId) {


        // 检查用户是否已经点赞
        boolean hasLiked = likesMapper.isUserLikedRecipe(userId, recipeId);
        if (hasLiked) {
            // 用户已点赞，执行取消操作
            int removed = likesMapper.removeLike(userId, recipeId);
            if (removed > 0) {
                recipeMapper.decrementLikeCount(recipeId);
                System.out.println("❌ 用户取消点赞成功");
                return 1;  // 取消点赞成功
            }
        } else {
            // 用户未点赞，执行点赞操作
            int added = likesMapper.addLike(userId, recipeId);
            if (added > 0) {
                recipeMapper.incrementLikeCount(recipeId);
                System.out.println("✅ 用户点赞成功");
                return 0;  // 点赞成功
            }
        }
        return -1; // 操作失败
    }

    @Override
    public boolean checkLikeStatus(Integer userId, Integer recipeId) {
        return likesMapper.isUserLikedRecipe(userId, recipeId);
    }

}
